package com.realgodo.site.service;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.providers.encoding.ShaPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.common.Attachment;
import com.realgodo.site.entity.security.User;
import com.realgodo.site.entity.space.Space;
import com.realgodo.site.entity.space.SpacePoint;
import com.realgodo.site.entity.vocation.UserVocation;
import com.realgodo.site.service.dic.AttachmentManager;
import com.realgodo.site.service.space.SpaceManager;
import com.realgodo.site.service.space.SpacePointManager;

/**
 * @author bijiqiang E-mail: bijiqiang@gmail.com
 * @version 创建时间：2009-12-13下午12:49:15
 * @since jdk1.5
 * @version 0.1
 */

@Service("userManager")
@Transactional
public class UserManager extends DefaultEntityManager<User, Long> {

	@Autowired
	private SpaceManager spaceManager;

	@Autowired
	protected SessionFactory sessionFactory;

	@Autowired
	private SpacePointManager spacePointManager;

	@Autowired
	private AttachmentManager attachmentManager;

	@Autowired
	private UserVocationManager userVocationManager;

	/**
	 * 用户注册
	 * 
	 * @param user
	 * @return
	 */
	public User createUser(User user) {
		PasswordEncoder passwordEncoder = new ShaPasswordEncoder();
		user.setPassword(passwordEncoder.encodePassword(user.getPassword(),
				null));
		user = (User) this.entityDao.saveMerge(user);

		Space space = new Space();
		space.setUser(user);
		space.setName(user.getLoginName());

		space.setDomain(user.getLoginName());
		space = (Space) this.spaceManager.saveMerge(space);

		SpacePoint spacePoint = new SpacePoint();
		spacePoint.setSpace(space);
		spacePointManager.save(spacePoint);

		return user;
	}

	/**
	 * 用户登录
	 * 
	 * @param user
	 * @return
	 */
	public User login(User user) {

		PasswordEncoder passwordEncoder = new ShaPasswordEncoder();
		String passwordzip = passwordEncoder.encodePassword(user.getPassword(),
				null);

		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select o from User o where  (o.loginName = '"
				+ user.getEmail().trim() + "' or o.email ='"
				+ user.getEmail().trim() + "') and o.password = '"
				+ passwordzip + "'" + "and o.enable=" + User.ENABLED;
		Query q = session.createQuery(hql);
		User userBack = (User) q.uniqueResult();
		return userBack;
	}

	/**
	 * 通过域名获取用户
	 * 
	 * @param domain
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public User getUserByDomain(String domain) {
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				User.class);
		c.add(Restrictions.eq("space.domain", domain));
		List<User> userList = c.list();
		return userList == null || userList.size() == 0 ? null : userList
				.get(0);
	}

	/**
	 * 编辑档案
	 * 
	 * @param user
	 * @return
	 */
	public User editUser(User user) {
		User editUser;
		if (null != user.getId()) {
			editUser = this.entityDao.get(user.getId());
			editUser.setBirthday(user.getBirthday());
			editUser.setMusic(user.getMusic());
			editUser.setPopStar(user.getPopStar());
			editUser.setName(user.getName());
			editUser.setEmail(user.getEmail());
			editUser.setHeight(user.getHeight());
			editUser.setWeight(user.getWeight());
			editUser.setQq(user.getQq());
			editUser.setPopStar(user.getPopStar());
			editUser.setOpus(user.getOpus());
			editUser.setSchoolRecord(user.getSchoolRecord());
			editUser.setTraining(user.getTraining());
			editUser.setAvatar(user.getAvatar());
			editUser.setCity(user.getCity());
			return (User) this.saveMerge(editUser);
		} else {
			return null;
		}

	}

	/**
	 * 获取用户分页列表的通用方法
	 * 
	 * @param userPage
	 * @param user
	 * @return
	 */
	public Page<User> findUsers(Page<User> userPage, User user) {
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				User.class);
		if (null != user) {
			if (user.getEnable() != User.ENABLED_DISENABLED_ALL) {
				c.add(Restrictions.eq("enable", user.getEnable()));
			}
			if (null != user.getLoginName() && !"".equals(user.getLoginName())) {
				c.add(Restrictions.like("loginName", user.getLoginName(),
						MatchMode.ANYWHERE));
			}
			if (null != user.getName() && !"".equals(user.getName())) {
				c.add(Restrictions.like("name", user.getName(),
						MatchMode.ANYWHERE));
			}
			if (user.getMeiMeiMan() != User.MEIMEI_MAN_ALL) {
				c.add(Restrictions.eq("meiMeiMan", user.getMeiMeiMan()));
			}
			if (user.getMeiMeiMember() != User.MEIMEI_MEMBER_ALL) {
				c.add(Restrictions.eq("meiMeiMember", user.getMeiMeiMember()));
			}
			if (user.getRecommend() != user.getRecommend()) {
				c.add(Restrictions.eq("recommend", user.getRecommend()));
			}
			if (null != user.getKey() && !"".equals(user.getKey())) {
				c.add(Restrictions.or(Restrictions.like("name", user.getKey(),
						MatchMode.ANYWHERE), Restrictions.like("loginName",
						user.getKey(), MatchMode.ANYWHERE)));
			}
		}

		c.addOrder(Order.desc("registDate"));

		userPage = this.entityDao.findByCriteria(userPage, c);
		UserVocation userVocation = null;// 开始封装用户暂态变量
		List<User> userTransients = userPage.getResult();
		for (User userTransient : userTransients) {
			userVocation = this.userVocationManager
					.getMajorUserVocation(userTransient.getId());
			if (null != userVocation) {
				userTransient.setVocationChinese(userVocation.getVocation()
						.getChName());
				userTransient.setVocationEnglish(userVocation.getVocation()
						.getEnName());
			}
		}
		userPage.setResult(userTransients);
		return userPage;
	}

	@SuppressWarnings("unchecked")
	public boolean checkUserName(String name) {
		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select o.id from User o where o.loginName = '" + name
				+ "'";
		Query q = session.createQuery(hql);
		List result = q.list();
		if (result == null || result.size() == 0) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public boolean checkUserEmail(String email) {
		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select o.id from User o where o.email = '" + email + "'";
		Query q = session.createQuery(hql);
		List result = q.list();
		if (result == null || result.size() == 0) {
			return true;
		}
		return false;
	}

	/** 激活用户 */
	public User activeUser(Long id, String activeCode) {
		User user = this.get(id);
		if (user.getEnable() == User.DISENABLED && user.getActiveCode() != null
				&& user.getActiveCode().equals(activeCode)) {
			user.setEnable(User.ENABLED);
			this.save(user);
			return user;
		}
		return null;
	}

	public User enableUser(Long id) {
		User user = this.get(id);
		user.setEnable(User.ENABLED);
		return (User) this.saveMerge(user);
	}

	public User lockUser(Long id) {
		User user = this.get(id);
		user.setEnable(User.DISENABLED);
		return (User) this.saveMerge(user);
	}

	public User manUser(Long id) {
		User user = this.get(id);
		user.setMeiMeiMan(User.MEIMEI_MAN_YES);
		return (User) this.saveMerge(user);
	}

	public User unManUser(Long id) {
		User user = this.get(id);
		user.setMeiMeiMan(User.MEIMEI_MAN_NO);
		return (User) this.saveMerge(user);
	}

	public User memberUser(Long id) {
		User user = this.get(id);
		user.setMeiMeiMember(User.MEIMEI_MEMBER_YES);
		return (User) this.saveMerge(user);
	}

	public User unMemberUser(Long id) {
		User user = this.get(id);
		user.setMeiMeiMember(User.MEIMEI_MEMBER_NO);
		return (User) this.saveMerge(user);
	}

	public User recommendUser(Long id) {
		User user = this.get(id);
		user.setRecommend(User.RECOMMEND_YES);
		return (User) this.saveMerge(user);
	}

	public User unRecommendUser(Long id) {
		User user = this.get(id);
		user.setRecommend(User.RECOMMEND_NO);
		return (User) this.saveMerge(user);
	}

	public User saveUserHead(String headPath, Long userId) {
		User user = this.entityDao.get(userId);

		Attachment head = new Attachment();
		head.setFullPath(headPath);
		head = (Attachment) this.attachmentManager.saveMerge(head);

		return (User) this.saveMerge(user);
	}

	/** 增加访问数 */
	public User visitCount(Long spaceId) {
		Space space = this.spaceManager.get(spaceId);
		User user = space.getUser();
		user.setVisitCount(user.getVisitCount() + 1);
		return (User) this.saveMerge(user);
	}

	/** 获取用于页面展示的User instance */
	public User getUserForDisplay(Long userId) {
		User _user = this.get(userId);
		UserVocation userVocation = this.userVocationManager
				.getMajorUserVocation(userId);
		if (null != userVocation) {
			_user.setVocationChinese(userVocation.getVocation().getChName());
			_user.setVocationEnglish(userVocation.getVocation().getEnName());
		}
		return _user;
	}

	/**
	 * 是否上传头像
	 * @param mySpace
	 * @return
	 */
	public Boolean hasUpdateAvatar(Space mySpace) {
		return (mySpace.getUser().getAvatar() != null && !mySpace.getUser()
				.getAvatar().isEmpty());
	}
}
